import 'package:flutter/material.dart';
import 'package:uuid/uuid.dart';
import '../data/user_repository.dart';
import '../entity/user.dart';

class UserProvider extends ChangeNotifier {
  final UserRepository _userRepository = UserRepository();

  User? _currentUser;
  User? get currentUser => _currentUser;

  bool _isLoading = false;
  bool get isLoading => _isLoading;

  String? _errorMessage;
  String? get errorMessage => _errorMessage;


  //使用账号和密码登录
  //返回 true 表示登录成功，false 表示失败
  Future<bool> login(String account, String password) async {
    _setLoading(true);
    _clearError();

    try {
      final user = await _userRepository.getUserByAccount(account);
      if (user != null && user.password == password) {
        _currentUser = user;
        _setLoading(false);
        return true;
      } else {
        _errorMessage = "账号或密码错误";
        _setLoading(false);
        return false;
      }
    } catch (e) {
      _errorMessage = "发生未知错误: $e";
      _setLoading(false);
      return false;
    }
  }

  //注册新用户
  Future<bool> register({
    required String account,
    required String name,
    required String password,
  }) async {
    _setLoading(true);
    _clearError();

    try {
      //检查账号是否已存在
      final existingUser = await _userRepository.getUserByAccount(account);
      if (existingUser != null) {
        _errorMessage = "该账号已经被注册";
        _setLoading(false);
        return false;
      }

      //创建新用户
      final newUser = User(
        id: const Uuid().v4(), //生成一个唯一的ID
        account: account,
        name: name,
        password: password,
        avatar: '',
        balance: 0.0,
      );

      await _userRepository.insert(newUser);
      //注册成功后自动登录
      _currentUser = newUser;
      _setLoading(false);
      return true;
    } catch (e) {
      _errorMessage = "注册失败: $e";
      _setLoading(false);
      return false;
    }
  }

  //用户登出
  void logout() {
    _currentUser = null;
    notifyListeners();
  }


  void _setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }

  void _clearError() {
    if (_errorMessage != null) {
      _errorMessage = null;
      //这里可以不用 notifyListeners，因为通常会立即跟随一个 setLoading(true)
    }
  }
}